package gui;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;

/**
 * DisposableDialog is same as JDialog but it can also be disposed with Enter
 * and Esc keys. Moreover it is displayed at center of its parent frame.
 */
public class DisposableDialog extends JDialog {

    DisposableDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);

        rootPane.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),
                "escapeCloseWindow");
        rootPane.getActionMap().put("escapeCloseWindow", disposeWindow);
        rootPane.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0),
                "enterCloseWindow");
        rootPane.getActionMap().put("enterCloseWindow", disposeWindow);
    }

    @Override
    public void setVisible(boolean b) {

        // Display on center
        centerFrame();
        super.setVisible(b);
    }

    /**
     * Setting dispose keys Esc and Enter at component given on parameter.
     *
     * @param c
     */
    protected void setDisposeKeys(JComponent... components) {
        for (JComponent c : components) {
            c.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),
                    "escapeCloseWindow");
            c.getActionMap().put("escapeCloseWindow", disposeWindow);
            c.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0),
                    "enterCloseWindow");
            c.getActionMap().put("enterCloseWindow", disposeWindow);
        }
    }

    /**
     * Set location of the window in center of parent
     */
    private void centerFrame() {
        int x;
        int y;
        // Find out our parent 
        Component myParent = this.getParent();
        Point topLeft = myParent.getLocation();
        Dimension parentSize = myParent.getSize();

        Dimension mySize = getSize();

        x = topLeft.x + parentSize.width / 2 - mySize.width / 2;
        y = topLeft.y + parentSize.height / 2 - mySize.height / 2;

        setLocation(x, y);
    }
    private Action disposeWindow = new AbstractAction() {

        @Override
        public void actionPerformed(ActionEvent e) {
            DisposableDialog.this.setVisible(false);
        }
    };
}
